<?php

namespace addons\miniform\controller;

use addons\miniform\model\Project;
use addons\miniform\model\Staff;
use addons\third\model\Third;
use think\Config;
use think\Validate;

/**
 * 会员
 */
class User extends Base
{
    protected $noNeedLogin = ['getSigned'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 个人中心
     */
    public function index()
    {
        $apptype = $this->request->param('apptype');
        $platform = $this->request->param('platform');
        $logincode = $this->request->param('logincode');

        $info = $this->auth->getUserInfo();
        $info['avatar'] = cdnurl($info['avatar'], true);
        $signin = get_addon_info('signin');

        $info['is_install_signin'] = ($signin && $signin['state']);
        $info['is_staff'] = (bool)Staff::where('user_id', $this->auth->id)->find();
        $firstlogin = $this->auth->jointime === $this->auth->logintime;

        //判断是否显示昵称更新提示
        $profilePrompt = false;
        $config = get_addon_config('miniform');
        if ($config['porfilePrompt'] === 'firstlogin') {
            $profilePrompt = $this->auth->jointime === $this->auth->logintime;
        } elseif ($config['porfilePrompt'] === 'everylogin') {
            $profilePrompt = true;
        } elseif ($config['porfilePrompt'] === 'disabled') {
            $profilePrompt = false;
        }
        $showProfilePrompt = false;
        if ($profilePrompt) {
            $showProfilePrompt = !$info['nickname'] || stripos($info['nickname'], '微信用户') !== false || preg_match("/^\d{3}\*{4}\d{4}$/", $info['nickname']);
        }

        $openid = '';
        //如果有传登录code，则获取openid
        if ($logincode) {
            $json = (new \addons\miniform\library\Wechat\Service())->getWechatSession($logincode);
            $openid = $json['openid'] ?? '';
        }
        $this->success('', [
            'userInfo'          => $info,
            'openid'            => $openid,
            'showProfilePrompt' => $showProfilePrompt
        ]);
    }


    /**
     * 个人资料
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username', "");
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar');
        if (!$nickname) {
            $this->error("用户名和昵称不能为空");
        }
        if (strlen($bio) > 100) {
            $this->error("签名太长了！");
        }
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }

        $avatar = str_replace(cdnurl('', true), '', $avatar);

        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();

        $this->success('修改成功！');
    }

    /**
     * 保存头像
     */
    public function avatar()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->post('avatar');
        if (!$avatar) {
            $this->error("头像不能为空");
        }

        $avatar = str_replace(cdnurl('', true), '', $avatar);
        $user->avatar = $avatar;
        $user->save();
        $this->success('修改成功！');
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), ['__token__' => $this->request->token()]);
    }

    /**
     * 分享配置参数
     */
    public function getSigned()
    {
        $url = $this->request->param('url', '', 'trim');
        $js_sdk = new \addons\miniform\library\Jssdk();
        $data = $js_sdk->getSignedPackage($url);
        $this->success('', $data);
    }

    /**
     * 我的项目列表
     */
    public function getProjectList()
    {
        $param = $this->request->param();
        $limit = 10;
        if (isset($param['limit'])) {
            $limit = $param['limit'];
        }
        $staff = Staff::where('user_id', $this->auth->id)->find();
        if (!$staff) {
            $this->error("暂无核销权限(code:1001)");
        }
        $data = Project::field('table,applyfields', true)
            ->where('is_verification', 1)
            ->where(function ($query) use ($staff) {
                if ($staff['projectdata'] !== '*') {
                    $query->where('id', 'in', array_filter(explode(',', $staff['projectdata'])));
                }
            })
            ->where(function ($query) use ($param) {
                $query->where('status', 'normal');
                if (!empty($param['category_id'])) {
                    $query->where('category_id', $param['category_id']);
                }
                if (!empty($param['title'])) {
                    $query->where('title', 'like', '%' . $param['title'] . '%');
                }
                if (!empty($param['keyword'])) {
                    $query->where('title', 'like', '%' . $param['keyword'] . '%');
                }
            })->order('id desc')->paginate($limit);
        foreach ($data as $res) {
            $res->append(['image', 'images_text']);
            $res->hidden(['images', 'createtime', 'updatetime', 'deletetime', 'table', 'begintime', 'endtime']);
        }
        $this->success('', $data);
    }
}
